package tw.com.test01;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.ListView;
import android.widget.TextView;

public class MultiChoiceDialog{

	ArrayList<String> lstReturn=new ArrayList<String>();

	protected TextView view;

	private Context context;
	private String title;
	private String[] list;

	public MultiChoiceDialog(Context context,TextView view,String title,String[] list){
		this.view=view;
		this.context=context;
		this.title=title;
		this.list=list.clone();
	}

	private AlertDialog create(){
		AlertDialog dialog;
		boolean[] listState=new boolean[list.length];
		for(int i=0;i<list.length;i++){
			listState[i]=false;
			for(int j=0;j<lstReturn.size();j++){
				if(list[i]==lstReturn.get(j)){
					listState[i]=true;
					break;
				}
			}
		}
		
		// 以 Builder 建立 AlertDialog
		dialog= new AlertDialog.Builder(context)
			.setTitle(title)
			.setMultiChoiceItems(list,listState,new DialogInterface.OnMultiChoiceClickListener(){
				// 若不加此Listener , 在點選CheckBox時沒反應 
				public void onClick(DialogInterface dialog,int whichButton, boolean isChecked){}
			})
			.setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int whichButton) {
					String strReturn="";
					ListView listView;
					listView=((AlertDialog)dialog).getListView();
					lstReturn.clear();
					for(int i=0;i<listView.getCount();i++){
						if(listView.getCheckedItemPositions().get(i)){
							lstReturn.add(listView.getAdapter().getItem(i).toString());
							strReturn+=(strReturn==""?"":",")+lstReturn.get(lstReturn.size()-1);
						}
					}
					setText(strReturn);
					dialog.dismiss();	
				}				
			})
			.setNegativeButton(android.R.string.cancel, null)
			.create();
		return dialog;
	}
	
	void show(){
		boolean checked;
		this.create().show();
	}
	
	void selectAll(){
		String strReturn="";
		lstReturn.clear();
		for(int i=0;i<list.length;i++){
			lstReturn.add(list[i]);
			strReturn+=(strReturn==""?"":",") + list[i];
		}
		setText(strReturn);
	}
	void select(String[] choice){
		String strReturn="";
		lstReturn.clear();
		setText("");
		for(int i=0;i<list.length;i++){
			for(int j=0;j<choice.length;j++){
				if(list[i]==choice[j]){
					lstReturn.add(list[i]);
					strReturn+=(strReturn==""?"":",") + list[i];
				}
			}
		}
		setText(strReturn);
	}
	public void selectNone(){
		lstReturn.clear();
		setText("");
	}
	public String[] toArray(){
		return ((String[])lstReturn.toArray());
	}
	
	// 將建構時傳入 TextView 的內容設為所選資料  
	private void setText(String text){
		if(view==null) return;
		view.setText(text);
	}
	
}
